package org.linuxsogood.boot.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author honway.liu
 * @date 2019/12/5 10:21 下午
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 连接就绪
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接就绪, 开始发送消息");
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hi server.", CharsetUtil.UTF_8));
    }

    /**
     * 当通道有事件可读取时触发
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        log.info("接收到服务端返回的消息:{}", buf.toString(CharsetUtil.UTF_8));
    }
}
